#include "Malloc.h"

ObjectPool<Span> SpanList::pool;

void *ConcurrentMalloc(size_t size)
{
    if (size <= MAX_SIZE)
    {
        if (pThreadCache == nullptr) {
            static std::mutex mtx;
            static ObjectPool<ThreadCache> pool;
            mtx.lock();
            pThreadCache = pool.New();
            mtx.unlock();
        }
        return pThreadCache->Allocte(size);
    }else{
        size_t alignSize = SizeClass::RoundUp(size);
        size_t pagenum = alignSize >> PAGE_SHIFT;
        PageCache::GetPageCacheInstance().Lock();
        Span *span = PageCache::GetPageCacheInstance().NewSpan(pagenum);
        span->objsize = alignSize;
        span->isUse = true;
        PageCache::GetPageCacheInstance().Unlock();
        return (void *)(span->pageid << PAGE_SHIFT);
    }
    assert(false);
}


void ConcurrentFree(void *ptr)
{
    size_t pageid = (PAGE_ID)ptr >> PAGE_SHIFT;
    Span *span = PageCache::GetPageCacheInstance().GetIdToSpan(pageid);

    size_t size = span->objsize;
    if (size <= MAX_SIZE)
    {
        pThreadCache->Deallocte(ptr, size);
    }else{
        PageCache::GetPageCacheInstance().ReleaseSpanToPageCache(span);
    }
}